import { t } from 'i18next'
import { StyledViewWrap, DeleteIcon, StyledWrapBlock } from './style'
import shallow from 'zustand/shallow'
import { AddStyleModal } from '../AddStyleModal'
import { FC } from 'react'
import { useMeetingTVWallStore } from '../store'
import { Modal } from '@kedacom/react-next'
import { fetchGetStyleById } from '@/api/create/tvwall'
import { BoxInfoEntity, boxPositionsEntity } from '../interface'
import { initOneTvwall } from '../store.combine'
const View: FC = () => {
	const {
		update,
		my_used_style,
		correct_style,
		config,
		style_map,
		show_mt_name,
		operate_correct_style_info,
		isNeedUpdate,
		mode,
		pollPlanOptions,
		pollPlanValue,
		pollTimes,
		unlimited,
		pollMembers,
		pollIntervalOptionsVal,
		pollInterval,
	} = useMeetingTVWallStore(
		(state) => ({
			update: state.update,
			my_used_style: state.used_style_map,
			correct_style: state.correct_style,
			config: state.config,
			style_map: state.style_map,
			show_mt_name: state.show_mt_name,
			operate_correct_style_info: state.operate_correct_style_info,
			isNeedUpdate: state.isNeedUpdate,
			mode: state.mode,
			pollPlanOptions: state.pollPlanOptions,
			pollPlanValue: state.pollPlanValue,
			pollTimes: state.pollTimes,
			unlimited: state.unlimited,
			pollMembers: state.pollMembers,
			pollInterval: state.pollInterval,
			pollIntervalOptionsVal: state.pollIntervalOptionsVal,
		}),
		shallow
	)
	/**去除掉删除风格（会议余下使用的风格） */
	const getRemainingMyUsedStyle = (_id: string): Array<BoxInfoEntity> => {
		let _result = my_used_style.filter((value) => {
			return value?.id !== _id
		})
		return _result
	}
	/**新增电视墙*/
	const handleAddCallBack = async (add_styles: Array<BoxInfoEntity>) => {
		if (add_styles.length > 0) {
			/**新增电视墙风格*/
			let _styles = add_styles
				? add_styles.map((item) => {
						return { id: item.id, name: item.name, positions: item.positions }
				  })
				: []
			/**已存在的风格 */
			let my_used_style_ids = my_used_style.map((item) => item.id)
			/**新增风格 */
			_styles = _styles.filter((item) => !my_used_style_ids.includes(item.id))
			/**为新增风格设置缓存*/
			for (let i = 0; i < _styles.length; i++) {
				let target = _styles[i]
				let result = {
					mode: mode,
					show_mt_name: show_mt_name ?? 0,
					style_id: target.id,
					members: [],
					batch_poll:
						mode === 1
							? null
							: {
									id: '',
									mode: 1,
									name:
										pollPlanValue === '0'
											? ''
											: pollPlanOptions.find((item) => item.value === pollPlanValue)?.label ?? '',
									keep_time:
										pollIntervalOptionsVal !== 0 ? pollIntervalOptionsVal : Number(pollInterval),
									num: unlimited ? 0 : Number(pollTimes),
									members: pollMembers.map((item) => {
										return {
											account: item.account,
											account_type: item.account_type,
											name: item.name,
											parent_id: item.parent_id,
										}
									}),
							  },
				}
				let source = useMeetingTVWallStore.getState().operate_correct_style_info
				source[target.id] = result
				update({ operate_correct_style_info: source })
			}
			var _arr = [...my_used_style, ..._styles]
			if (!correct_style) {
				/**证明要渲染当前数据(需要获取当前通道的最新状态) */
				const res = await fetchGetStyleById(_arr[0].id ?? '')
				if (res.success) {
					update({
						correct_style_positions: res.details,
						correct_style: _arr[0].id,
					})
				}
			}
			update({ used_style_map: _arr, isNeedUpdate: !isNeedUpdate })
		}
	}
	/**删除指定风格的缓存*/
	const deleteCash = (_id: string) => {
		/**获取所有缓存数据*/
		let all_cash = operate_correct_style_info
		/**删除对应风格缓存*/
		delete all_cash[_id]
		/**更新缓存 */
		update({ operate_correct_style_info: all_cash })
	}
	/**删除电视墙风格 */
	const handleDeleteTVWallStyle = async (item: { id: string; name: string }) => {
		var m = Modal.confirm({
			content: t('确定删除所选电视墙风格？'),
			onOk: async () => {
				const _my_used_style = getRemainingMyUsedStyle(item.id)
				if (correct_style === item.id) {
					if (_my_used_style.length > 0) {
						let current_id = _my_used_style[0]?.id
						const res = await fetchGetStyleById(current_id ?? '')
						if (res.success) {
							update({
								correct_style_positions: res.details,
								used_style_map: _my_used_style,
								correct_style: current_id,
							})
						} else {
							update({
								correct_style_positions: [],
								used_style_map: _my_used_style,
								correct_style: current_id,
							})
						}
					} else {
						/**清空所有的电视墙风格 */
						update({ used_style_map: [], correct_style: '', correct_style_positions: [] })
					}
				} else {
					update({ correct_style: correct_style, used_style_map: _my_used_style })
				}
				deleteCash(item.id)
				m.hide()
			},
			onCancel: () => {
				m.hide()
			},
		})
	}
	/**切换电视墙风格*/
	const handleChangeStyle = async (_id: string) => {
		if (correct_style === _id) return
		let info = operate_correct_style_info[_id]
		console.log('获取对应的缓存数据', info)
		initOneTvwall(info as any)
	}
	/**计算小方块位置 */
	const returnNormalWrap = (positionItem: boxPositionsEntity) => {
		const { box_x, box_y, box_width, box_height } = positionItem
		let rate = config.currentviewW / config.containerW
		let _left = box_x * rate
		let _right = box_y * rate
		let _width = box_width * rate
		let _height = box_height * rate
		return <StyledWrapBlock left={_left} top={_right} width={_width} height={_height}></StyledWrapBlock>
	}
	return (
		<StyledViewWrap className="tvwall-style-wrap">
			<ul className="tvwall-style-list">
				{my_used_style &&
					my_used_style.map((item, myUsedIndex) => {
						if (item) {
							const positions = style_map[item.id]?.positions
							if (!positions) {
								return <></>
							}
							return (
								<li
									className={`tvwall-style tvwall-style-btn ${
										correct_style === item.id ? 'selected' : ''
									}`}
									onClick={() => {
										handleChangeStyle(style_map[item.id].id)
									}}
									key={myUsedIndex}
								>
									<span className="currentview">
										{positions.map((positionItem, positionIndex) => {
											return <div key={positionIndex}>{returnNormalWrap(positionItem)}</div>
										})}
									</span>
									<span className="TVstyleText" title={item.name}>
										{item.name}
									</span>
									<span className="box-menu-wrap">
										<span
											onClick={(e) => {
												e.stopPropagation()
												handleDeleteTVWallStyle(item)
											}}
										>
											<DeleteIcon></DeleteIcon>
										</span>
									</span>
								</li>
							)
						} else {
							return <></>
						}
					})}
			</ul>
			<div
				className="tvwall-style add-tvwall-style"
				onClick={() => {
					update({ isAddStyleModalOpen: true })
				}}
			>
				<span className="tvwall-style-icon"></span>
				<span className="tvwall-style-text">{t('添加电视墙')}</span>
			</div>
			<AddStyleModal callBack={handleAddCallBack} />
		</StyledViewWrap>
	)
}
export default View
